<template>
  <div>
    <h1>WebSocket 测试</h1>
    <button @click="sendMessage">发送普通消息</button>
    <button @click="sendComplexMessage">发送复杂消息</button>
    <button @click="requestMatch">请求匹配</button>
    <div>
      <input v-model="customMessage" placeholder="输入自定义消息" />
      <button @click="sendCustomMessage">发送自定义消息</button>
    </div>
    <div v-for="msg in messages" :key="msg" class="message">
      {{ msg }}
    </div>
  </div>
</template>

<script>
export default {
  name: "WebSocketTest",
  data() {
    const userId = Math.random().toString(36).substring(2, 15);
    const username = `User_${userId}`;
    return {
      messages: [],
      socket: null,
      userId,
      username,
      roomId: null,
      customMessage: ""  // 添加一个数据属性用于绑定输入框
    };
  },
  mounted() {
    this.connect();
  },
  methods: {
    connect() {
      this.socket = new WebSocket("ws://localhost:8081/socket.io");

      this.socket.onopen = () => {
        console.log("WebSocket 连接成功！");
        this.messages.push("连接成功！");
        this.sendUserInfo();
      };

      this.socket.onmessage = (event) => {
        try {
          const message = JSON.parse(event.data);
          console.log("收到消息：", message);

          switch (message.type) {
            case "MATCH_SUCCESS":
              this.roomId = message.roomId;
              this.messages.push(`匹配成功！房间 ID: ${this.roomId}`);
              break;
            case "ROOM_MESSAGE":
              this.messages.push(`收到房间消息：${message.text}`);
              break;
            case "MATCH_FAILED":
              this.messages.push(`匹配失败：${message.reason}`);
              break;
            case "ERROR":
              this.messages.push(`错误：${message.reason}`);
              break;
            default:
              this.messages.push(`未知消息类型：${message.type}`);
          }
        } catch (error) {
          console.error("解析消息失败：", error);
          this.messages.push(`收到无法解析的消息：${event.data}`);
        }
      };

      this.socket.onerror = (error) => {
        console.error("WebSocket 错误：", error);
        this.messages.push(`发生错误：${error.message}`);
      };

      this.socket.onclose = (event) => {
        console.log("WebSocket 连接关闭：", event);
        this.messages.push(`连接关闭：${event.reason}`);
      };
    },
    sendUserInfo() {
      const message = {
        userId: this.userId,
        username: this.username,
      };
      this.socket.send(JSON.stringify(message));
    },
    sendMessage() {
      if (this.roomId) {
        const message = {
          type: "ROOM_MESSAGE",
          roomId: this.roomId,
          text: "Hello from Vue.js"
        };
        this.socket.send(JSON.stringify(message));
        this.messages.push(`已发送：${JSON.stringify(message)}`);
      } else {
        this.messages.push("请先请求匹配并加入房间");
      }
    },
    sendComplexMessage() {
      if (this.roomId) {
        const message = {
          type: "ROOM_MESSAGE",
          roomId: this.roomId,
          text: "这是一个复杂消息",
          userId: this.userId,
          userName: this.username,
          actions: ["action1", "action2"],
          details: {
            timestamp: Date.now(),
            status: "active"
          }
        };
        this.socket.send(JSON.stringify(message));
        this.messages.push(`已发送：${JSON.stringify(message)}`);
      } else {
        this.messages.push("请先请求匹配并加入房间");
      }
    },
    requestMatch() {
      const message = {
        type: "MATCH_REQUEST",
        userId: this.userId,
        username: this.username,
      };
      this.socket.send(JSON.stringify(message));
      this.messages.push("已发送匹配请求");
    },
    sendCustomMessage() {
      if (this.roomId && this.customMessage.trim()) {
        const message = {
          type: "ROOM_MESSAGE",
          roomId: this.roomId,
          text: this.customMessage
        };
        this.socket.send(JSON.stringify(message));
        this.messages.push(`已发送自定义消息：${this.customMessage}`);
        this.customMessage = "";  // 清空输入框
      } else {
        this.messages.push("请先请求匹配并加入房间，或输入有效消息内容");
      }
    }
  },
  beforeDestroy() {
    if (this.socket) {
      this.socket.close();
    }
  },
};
</script>

<style scoped>
.message {
  margin: 10px 0;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
}
</style>